from neo4j import GraphDatabase  # pip install neo4j-driver
from config import NEO4J_CONFIG


def cat_and_mouse(tx, cat_name, mouse_name):
    r = tx.run("MERGE (a:Cat{name: $cat_name})" 
           "MERGE (b:Mouse{name: $mouse_name})" 
           "MERGE (a)-[r:and]-(b)", cat_name=cat_name, mouse_name=mouse_name)

    # eo4j.exceptions.ResultConsumedError: The result is out of scope.
    # The associated transaction has been closed. Results can only be used while the transaction is open.
    show_record(r)

    return r


def show_record(record):
    print(type(record))
    for i, el in enumerate(record):
        print(i, el)


if '__main__' == __name__:

    def _main():
        driver = GraphDatabase.driver(**NEO4J_CONFIG)

        if 0:
            with driver.session() as ss:
                cypher = "CREATE(c:Company) SET c.name='在线医生' RETURN c.name"
                record = ss.run(cypher)
                print(type(record))
                for i, el in enumerate(record):
                    print(i, el)

        with driver.session() as ss:
            print('Before tx')
            # DeprecationWarning: write_transaction has been renamed to execute_write
            # r = ss.write_transaction(cat_and_mouse, 'Tom', 'Jerry')
            r = ss.execute_write(cat_and_mouse, 'Tom', 'Jerry')
            print('After tx')

        print('All over')

    _main()
